import axios from 'axios'
import JSONbig from 'json-bigint'
import { Toast } from 'vant'
import Cookies from 'js-cookie'
import router from '@/router'
import Vue from 'vue'
import debounce from 'lodash/debounce'

const http = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 1000 * 180,
  withCredentials: true,
  transformResponse: [
    function (data) {
      try {
        return JSONbig.parse(data)
      } catch (err) {
        return data
      }
    }
  ]
})

http.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8'
    // config.headers['Access-Control-Allow-Origin'] = '*'
    config.headers.token = Cookies.get('token')
    // 防止缓存，GET请求默认带_t参数
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        ...{ _t: new Date().getTime() }
      }
      config.transformRequest = [function (data) {
        let ret = ''
        for (const it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }]
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  (response) => {
    if (response.data.code === 0) {
      response.data.msg = '操作成功'
    }
    if (response.data.code === 403) {
      Toast.fail('登录已失效')
      router.replace({ name: 'login' })
    }
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          debounce(
            Vue.prototype.$login().then(() => {
              // window.location.reload(true)
            })
          )
          break
        case 403:
          Toast.fail('登录已失效')
          router.replace({ name: 'login' })
          break
        case 500:
          Toast.fail('客户端请求参数异常')
          break
      }
    }
    return Promise.reject(error)
  }
)

export default http
